from django.template.defaulttags import URLNode

from django import template
register = template.Library()

class CourseURLNode(URLNode):
	def render(self, context):
		if 'course' in context and context['course'] and context['course'].course_id != '__default':
			course_id = self.course_id
			if self.args:
				#raise template.TemplateSyntaxError('course_url must use kwargs instead of args')
				first_arg = self.args[0].resolve(context)
				if first_arg != course_id.resolve(context) and first_arg != context['course'].course_id: self.args.insert(0,course_id)
			elif not self.kwargs:
				self.kwargs = {'course':course_id}
			elif not 'course' in self.kwargs:
				self.kwargs['course'] = course_id
		return super(CourseURLNode,self).render(context)
	
def course_url(parser, token):
	from django.template.defaulttags import url
	ReturnURLNode = url(parser,token)
	ReturnURLNode.__class__ = CourseURLNode
	ReturnURLNode.course_id = parser.compile_filter('course.course_id')
	return ReturnURLNode
register.tag('course_url', course_url)
